package net.llz.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import net.llz.model.UserDO;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
public class JWTUtil {

    private static final long EXPIRE= 1000 * 60 * 60 * 24 * 7 * 10;


    //令牌前缀
    private static final String TOKEN_PREFIX="vx_demo";
    private static final String SUBJECT="llz";
    //加密密钥
    private static final String SECRET="long";

    public static String geneJsonWebToken(UserDO userDO){
        if (userDO ==null){
            throw new NullPointerException("user对象是空");
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("id",userDO.getId())
                .claim("phone",userDO.getPhone())
                .claim("name",userDO.getName())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE))
                .signWith(SignatureAlgorithm.HS256,SECRET)
                .compact();

        token=TOKEN_PREFIX+token;

        return token;
    }


    public static Claims checkJWT(String token){

        try {
            final Claims claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX,"")).getBody();

            return  claims;
        }catch (Exception e){
            log.info("jwt 解密失败");
        return null;
        }
    }
}
